#ifdef linux
/**
 * @file test_rwlock.cpp
 * @date 2021/10/28 16:10
 * 
 * @author harrybao (harrybao@123u.com)
 * 
 * @brief 测试读写锁
 * 
 * @version v1.0.0
 * 
 * @copyright Copyright © 2021 harrybao All Rights Reserved
 * 
 * @par history:
 * <table>
 * <tr><th>Date                     <th>Version     <th>Author      <th>Description
 * <tr><td>2021/10/28 16:10         <td>1.0.0       <td>harrybao    <td>创建初始版本
 * </table>
 */

#include "thread/mutex/readwrite_lock.hpp"
#include <iostream>
#include <vector>
#include <thread>

hthread::readwrite_lock rwlock;

static int i = 0;

void run_read() {

  int n = 1;
  while (n--) {
    rwlock.rlock();
    // std::cout << "thread:" << std::this_thread::get_id() << 
    std::cout << " i:" << i << std::endl;

    // std::this_thread::sleep_for(std::chrono::milliseconds(20));
    rwlock.runlock();
  }
}

void run_write() {
  int n = 1;
  while (n--) {
    rwlock.wlock();
    i++;

    // std::this_thread::sleep_for(std::chrono::milliseconds(2));
    rwlock.wunlock();
  }
}

int main() {
  std::vector<std::thread*> thread_write_vec;
  std::vector<std::thread*> thread_read_vec;

  for (int i = 0; i < 200; ++i) {
    auto t = new std::thread(run_write);
    thread_write_vec.emplace_back(t);
  }

  for (int i = 0; i < 1000; ++i) {
    auto t = new std::thread(run_read);
    thread_read_vec.emplace_back(t);
  }

  for (auto &t: thread_write_vec) {
    if (t->joinable()) {
      t->join();
    }
  }
  
  for (auto &t: thread_read_vec) {
    if (t->joinable()) {
      t->join();
    }
  }

#ifdef DEBUG
  assert(rwlock.rcount() == 0);
  assert(rwlock.wcount() == 0);
  assert(rwlock.writing() == false);
#endif // DEBUG
 
  return 0;
}

#endif